import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input,  message, Button,Card,Checkbox ,Select,InputNumber, Divider} from 'antd';
import { connect } from 'dva';
import PropTypes from "prop-types";
import router from 'umi/router';
import * as R from 'ramda';


const transferOption = (arrayData = [], keyValue = ['value', 'label']) => R.map(
  item => <Select.Option key={item[keyValue[0]]}>{item[keyValue[1]]}</Select.Option>, arrayData);
const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 4 },
    sm: { span: 14 },
  },
};
@Form.create()
@connect((state:any) => ({
  dataPackageConfigData: state.dataPackageConfigData,
  loading: state.loading.models["dataPackageConfigData"],
  menu: state.menu,
}))
export default class DataPackageConfigEdit extends React.Component<any,any> {
  constructor(props:any) {
    super(props);
    this.state = {
    formValues: {},
    seriesOptions: [], // 车系列表
    nameOptions: [], //车型组列表
    codeOptions: [], //套餐编码
    flow: {}, // 套餐详情信息
    buttonLoading: false,
    brandOptions: [],
    brandId: '',
    };
  }

  static contextTypes = {
    permissions: PropTypes.array,
  };
  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        brandOptions:this.props.location.state.brandOption,
        brandId: this.props.location.state.brandId,
      });
    }
  }
  componentDidMount(){
    const record = JSON.parse(sessionStorage.getItem('dataPackageConfigData') || '{}');
    const { dispatch } = this.props;
    const { formValues } = this.state;
     // 获取套餐编码
   dispatch({
    type: 'dataPackageConfig/getData',
    payload: { url: '/mno/package/code/list'},
    callback: (e:any) => {
     if (e.statusCode === "0") {
       if(e.data){
         this.setState({
          codeOptions: e.data.map(e =>({
          name: e.name,
          code: e.code,
        }))
       })
       }
     } else {
       message.error(e.statusMessage);
     }
    }
    });
   // 获取车系数据
   const brandId = this.props.location && this.props.location.state.brandId;
   dispatch({
   type: 'dataPackageConfig/getDataWithRes',
   payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId },
   callback: (e:any) => {
    if (e.statusCode === "0") {
      if(e.data){
      this.setState({
       seriesOptions: e.data.map(e =>({
         seriesName: e.seriesName,
         seriesCode: e.seriesCode,
       })
       )
      })
    }
  } else {
    message.error(e.statusMessage);
  }
   }
   });
   // 获取初始车系对应的车型组列表信息
   this.props.dispatch({
    type: 'dataPackageConfig/postData',
    payload: { url: '/vehicle/group/findBySeriesCode', seriesCode: record.seriesCode},
    callback: (e:any) => {
      if (e.statusCode === "0") {
      if (e.data) {
        this.setState({
          nameOptions: e.data.map(e =>({
            name: e.name,
            groupCode: e.code,
          }))
         })
      } else {
        this.setState({
          nameOptions: [],
        });
      }
    } else {
      message.error(e.statusMessage);
    }
    },
  });
    // 获取详情信息
    const { form,} = this.props;
    dispatch({
      type: 'dataPackageConfig/postData',
      payload: { url: '/mno/package/findCfgBySeriesAndGroup',seriesCode: record.seriesCode, groupCode: record.groupTypeCode},
      // payload: { url: '/mno/package/findBySeriesAndGroup', brandId: 'DFPV', seriesCode: record.seriesCode, groupCode: record.groupTypeCode},
      callback: (res:any) => {
        if (res.statusCode === "0") {
          if(res.data){
          const data = res.data;
          this.setState({
            flow: res.data
          })
        form.setFieldsValue({
          seriesCode: record?.seriesCode,
          groupCode: record?.groupTypeCode,
          activeUser:  data?.activeUser ? data?.activeUser.toString() : '',
          activeUserDuration: data?.activeUserDuration,
          activeTestDriver: data?.activeTestDriver ? data?.activeTestDriver.toString() : '',
          activeShow: data?.activeShow ? data?.activeShow.toString() : '',
          activeInnerTest: data?.activeInnerTest ? data?.activeInnerTest.toString() : '',
          activeMedia: data?.activeMedia ? data?.activeMedia.toString() : '',
          remark: data?.remark,
          })
         }
        } else{
          message.error(res.statusMessage);
        }
      },
    })
  }
  componentWillUnmount() {
    const { dispatch } = this.props
    dispatch({
      type: 'http/clearData',
    })
    sessionStorage.removeItem('dataPackageConfigData');
  }
   // 通过车系查询车型组信息
   onSelect = (value:any) => {
    const { form} = this.props;
    if (value) {
      this.props.dispatch({
        type: 'dataPackageConfig/postData',
        payload: { url: '/vehicle/group/findBySeriesCode', seriesCode: value},
        callback: (e:any) => {
        if (e.statusCode === "0") {
          if (e.data) {
            this.setState({
              nameOptions: e.data.map(e =>({
                name: e.name,
                groupCode: e.code,
              }))
             })
          } else {
            this.setState({
              nameOptions: [],
            });
          }
      } else{
        message.error(e.statusMessage);
      }
    },
      });
    } else {
      this.setState({
        nameOptions: [],
      });
    }
    form.setFieldsValue({
      groupCode: ''
    })
  }
  handleCancel = () => {
    if (this.props.location && this.props.location.state) {
      const {pageObj , formValues, backUrl} = this.props.location.state;
      router.push({ pathname: backUrl, state: { pageObj: pageObj,sourceRouter: 'dataPackage', formValues } });
    } else {
      router.push({ pathname: '/remoteConfiguration/dataPackageConfig' , state: {sourceRouter: 'dataPackage'}});
    }
  }
  handleOk = () => {
    const { dispatch, form:{validateFields}} = this.props;
    const record = JSON.parse(sessionStorage.getItem('dataPackageConfigData')||'{}');
     validateFields((err:any, values:any) => {
      if (err) {
        return;
      }
      this.setState({ 
        buttonLoading: true ,
      }); 
      let params = {};
      params.seriesCode = values.seriesCode;
      params.groupCode = values.groupCode;
      params.activeUser = values.activeUser;
      params.activeUserDuration = values.activeUserDuration;
      params.activeTestDriver = values.activeTestDriver;
      params.activeShow = values.activeShow;
      params.activeInnerTest = values.activeInnerTest;
      params.activeMedia = values.activeMedia;
      params.remark = values.remark;
      params.oldSeriesCode = record.seriesCode;
      params.oldGroupCode = record.groupTypeCode;
      params.brandId = values.brandId;
      dispatch({
        type: 'dataPackageConfig/postObjWithRes',
        payload: { url: '/mno/package/new/batchUpdate', ...params },
        callback: (response:any) => {
          if (response.statusCode === "0") {
            message.success("操作成功！");
            this.handleCancel();
          } else {
            // message.error(response.statusMessage);
          }
          this.setState({ buttonLoading: false });
        }
      });
    });
  }
  checkFill = (rule, value, callback) => {
    const {form}=this.props;
    const activeUser = form.getFieldValue('activeUser');
    const activeInnerTest = form.getFieldValue('activeInnerTest');
    const activeShow = form.getFieldValue('activeShow');
    const activeTestDriver = form.getFieldValue('activeTestDriver');
    const activeMedia = form.getFieldValue('activeMedia');
    if (!(activeUser || activeInnerTest || activeShow || activeTestDriver || activeMedia)){
      callback('请至少选择一项填写！');
      return;
    }
    callback();
  }
  render() {
    const {buttonLoading,seriesOptions,nameOptions,codeOptions,} =this.state;
    const {form: { getFieldDecorator },} = this.props;
    return (
          <div>
            <Card bordered={false}>
            <Form layout="horizontal">
            <FormItem {...formItemLayout} label={<span>品牌&nbsp;</span>}>
              {getFieldDecorator('brandId', {
                 initialValue:this.state.brandId,
                 rules: [{ required: false, message: '请选择品牌' }],
              })(
                <Select placeholder="请选择" disabled={true}>
                  {transferOption(this.state.brandOptions, ['brandCode', 'brandName'])}
                </Select>,
              )}
            </FormItem>
              <FormItem
                {...formItemLayout}
                label={<span>车系&nbsp;</span>}
              >
                {getFieldDecorator('seriesCode', {
                  rules: [{ required: true, message: '请选择车系' }],
                })(
                  <Select
                  placeholder="请选择"
                  onChange={this.onSelect}
                >
                 {transferOption(seriesOptions, ['seriesCode', 'seriesName'])}
                </Select>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label={<span>车型组&nbsp;</span>}
              >
                 {getFieldDecorator('groupCode', {
                  rules: [{ required: true, message: '请选择车型组' }],
                })(
                  <Select
                  placeholder="请选择"
                >
                  {transferOption(nameOptions, ['groupCode', 'name'])}
                </Select>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label={<span>服务年限&nbsp;</span>}
              >
                 {getFieldDecorator('activeUserDuration', {
                  rules: [{ required: true, message: '请输入服务年限' }],
                })(
                    <InputNumber min={1} max ={100} placeholder="请输入服务年限" style={{ width: '25%' }}/>
                )}
                 <span className="ant-form-text">&nbsp;&nbsp;月</span>
              </FormItem>
              <FormItem
                     {...formItemLayout}
                     label={<span>激活类型&nbsp;</span>}
                    //  noStyle
                   >
                    {getFieldDecorator('activeType', {
                      rules:[{ required: true, validator: this.checkFill }]
                })(   
                    <div></div>
                 )}
             </FormItem>
             <Divider />
             <FormItem
                     {...formItemLayout}
                     label={<span>用户&nbsp;</span>}
                   >
                     {getFieldDecorator('activeUser', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                        <Select
                        placeholder="请选择"
                        allowClear
                      >
                       {transferOption(codeOptions, ["code", "name"])}
                      </Select>
                    )}
             </FormItem>
             <FormItem
                     {...formItemLayout}
                     label={<span>内部测试&nbsp;</span>}
                   >
                     {getFieldDecorator('activeInnerTest', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                        <Select
                        placeholder="请选择"
                        allowClear
                      >
                       {transferOption(codeOptions, ['code', 'name'])}
                      </Select>
                    )}
             </FormItem>
             <FormItem
                     {...formItemLayout}
                     label={<span>展车&nbsp;</span>}
                   >
                     {getFieldDecorator('activeShow', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                        <Select
                        placeholder="请选择"
                        allowClear
                      >
                        {transferOption(codeOptions, ['code', 'name'])}
                      </Select>
                    )}
             </FormItem>
             <FormItem
                     {...formItemLayout}
                     label={<span>试乘试驾&nbsp;</span>}
                   >
                     {getFieldDecorator('activeTestDriver', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                        <Select
                        placeholder="请选择"
                        allowClear
                      >
                       {transferOption(codeOptions, ['code', 'name'])}
                      </Select>
                    )}
             </FormItem>
             <FormItem
                     {...formItemLayout}
                     label={<span>媒体车&nbsp;</span>}
                   >
                     {getFieldDecorator('activeMedia', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                        <Select
                        placeholder="请选择"
                        allowClear
                      >
                        {transferOption(codeOptions, ['code', 'name'])}
                      </Select>
                    )}
             </FormItem>
             <Divider />
              <FormItem
                {...formItemLayout}
                label={<span>备注&nbsp;</span>}
              >
                {getFieldDecorator('remark', {
                  rules: [{ required: false, message: '请输入套餐备注' }],
                })(
                  <TextArea placeholder="请输入" rows={4} />
                )}
              </FormItem>
              <FormItem wrapperCol={{ offset: 8, span: 16 }}>
                   <Button type="primary" htmlType="submit" loading={buttonLoading} onClick={this.handleOk} > 保存 </Button>
                    <Button style={{ marginLeft: 10 }} onClick={this.handleCancel}> 取消 </Button>
              </FormItem>
            </Form>
            </Card>
          </div>
    );
  }
}
